package com.iring.service.common;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.iring.dao.vos.GetSuiteDao;
import com.iring.domain.vos.suite.InfoSuite;
import com.iring.domain.vos.suite.SuiteInfo;

/**
 * 套餐工具类
 *
 * @author wanggan
 */
@Component
@ConditionalOnClass(GetSuiteDao.class)
public class AllSuiteService {

    @Autowired
    GetSuiteDao getSuiteDao;

    private static final Logger logger = LoggerFactory.getLogger(AllSuiteService.class);

    private static Cache<Integer, InfoSuite> cache = CacheBuilder.newBuilder()
            .maximumSize(50)
            .expireAfterWrite(24, TimeUnit.HOURS)
            .build();

    /**
     * 获取单个套餐详情
     *
     * @param suiteId
     *            套餐id
     * @return 套餐对象 {@link InfoSuite}
     */
    public synchronized InfoSuite getSingleSuiteCache(Integer suiteId) {
        return cache.getIfPresent(suiteId);
    }


    /**
     * 获取所有的套餐
     *
     * @return 所有的套餐信息
     */
    public Collection<InfoSuite> getAllSuiteCache() {
        ConcurrentMap<Integer, InfoSuite> map = cache.asMap();
        return map.values();
    }

    /**
     * 清除所有的套餐cache
     */
    public void cleanAllSuite() {
        cache.cleanUp();
    }

    /**
     * 刷新所有的套餐详情
     */
    public void loadAllSuite() {
        // 请求设置全局的套餐信息
        SuiteInfo getSuite = getSuiteDao.GetAllSuite();
        Assert.notNull(getSuite, "getSuite must not be null");

        if(null == getSuite){
            return;
        }

        if (getSuite.getRetCode() == 0.0) {

            List<InfoSuite> list = getSuite.getInfoSuites();

            if (list.size() > 0) {
                Map<Integer, InfoSuite> mapInfoSuite = list.stream().
                        collect(Collectors.toMap(InfoSuite::getId, (p) -> p));

                cache.putAll(mapInfoSuite);
                logger.info("load all suite success...");
            } else {
                logger.info("no suite msg..");
            }
        } else {
            logger.info("请求数据异常={}", getSuite);
        }
    }
}
